package zhihuilan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import zhihuilan.common.WxMiniResponse;
import zhihuilan.common.enums.RedisKeyEnum;
import zhihuilan.common.enums.ResultEnum;
import zhihuilan.common.utils.RedisCache;
import zhihuilan.dto.MyPcdDto;
import zhihuilan.entity.*;
import zhihuilan.mapper.*;
import zhihuilan.service.MyConfigService;
import zhihuilan.service.MyPcdService;
import zhihuilan.service.ToolService;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static zhihuilan.common.utils.BaiduMapUtils.lnglat2addr;
import static zhihuilan.common.utils.BaiduMapUtils.lnglat2address;
import static zhihuilan.common.utils.ToolsUtils.*;


@Service
public class ToolServiceImpl implements ToolService {

    @Autowired
    private  MyConfigMapper myConfigMapper;

    @Autowired
    private MyStaffMapper myStaffMapper;

    @Autowired
    private MySmsMapper mySmsMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MyPcdService myPcdService;

    @Autowired
    private MyPcdMapper myPcdMapper;

    @Autowired
    private MyCategoryAppMapper myCategoryAppMapper;

    @Override
    public  WxMiniResponse sendsms(Map map) throws Exception {

        if(!isMobile(map.get("mobile").toString())){
            return  WxMiniResponse.error(ResultEnum.NO_MOBILE.getKey(), ResultEnum.NO_MOBILE.getValue());
        }
        QueryWrapper<MySms> smsQueryWrapper = new QueryWrapper<>();
        smsQueryWrapper.eq("status",0);
      //  smsQueryWrapper.eq("type",map.get("type").toString());
        smsQueryWrapper.eq("telephone",map.get("mobile").toString());
        smsQueryWrapper.gt("addtime",new Date(new Date().getTime()-300000));
        smsQueryWrapper.orderByDesc("id");
        MySms mySms = mySmsMapper.selectOne(smsQueryWrapper);

        Map sendsms = redisCache.getCacheObject(RedisKeyEnum.REDIS_KEY_SENDSMS.getKey());
        MyStaff staff = myStaffMapper.selectOne( new QueryWrapper<MyStaff>().eq("telephone",map.get("mobile").toString()));
        if(!ObjectUtils.isEmpty(staff)&&staff.getId()>0) {
            if (ObjectUtils.isEmpty( sendsms)||ObjectUtils.isEmpty( sendsms.get("smsFix") )) {
                QueryWrapper<MyConfig> wrapper = new QueryWrapper<>();
                wrapper.eq("`group`", 3);
                wrapper.eq("status", 1);
                wrapper.orderByDesc("sort");
                List<MyConfig> list = myConfigMapper.selectList(wrapper);
                Map configMap = new HashMap();
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getName().equals("sms_username")) {
                        configMap.put("keyId", list.get(i).getValue());
                    } else if (list.get(i).getName().equals("sms_userpwd")) {
                        configMap.put("KeySecret", list.get(i).getValue());
                    } else if (list.get(i).getName().equals("audit_fail_tpl")) {
                        configMap.put("fail", list.get(i).getValue());
                    } else if (list.get(i).getName().equals("audit_succ_tpl")) {
                        configMap.put("succ", list.get(i).getValue());
                    } else if (list.get(i).getName().equals("sms_fix")) {
                        configMap.put("smsFix", list.get(i).getValue());
                    } else if (list.get(i).getName().equals("sms_tpl_code")) {
                        configMap.put("code", list.get(i).getValue());
                    }
                }
                redisCache.setCacheObject(RedisKeyEnum.REDIS_KEY_SENDSMS.getKey(), configMap,2,TimeUnit.HOURS);
                sendsms = redisCache.getCacheObject(RedisKeyEnum.REDIS_KEY_SENDSMS.getKey());
            }
            Config config = new Config()
                    .setAccessKeyId(sendsms.get("keyId").toString())
                    .setAccessKeySecret(sendsms.get("KeySecret").toString());
            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            // 创建短信服务客户端
            Client client = new Client(config);
            // 创建短信发送请求
            String code = "";
            String param = "";
            String code1 = "";
            if(!ObjectUtils.isEmpty(map.get("code"))){
                param = "{\"name\":\""+staff.getUserreal()+"\"}";
                code1 = sendsms.get("fail").toString();
                if(map.get("mobile").equals("1")){
                    code1 = sendsms.get("fail").toString();
                }
            }else {
                if(mySms!=null){
                    return  WxMiniResponse.error(2012,"已发送验证码，请注意！");
                }
                code1 = sendsms.get("code").toString();
                Random rand = new Random();
                code = (rand.nextInt(9000)+1000)+"";
                param = "{\"code\":\""+code+"\"}";
                MySms sms = new MySms();
                sms.setCode(code);
                sms.setTelephone(map.get("mobile").toString());
                sms.setStatus(0);
                sms.setType(1);
                mySmsMapper.insert(sms);
            }
            SendSmsRequest sendSmsRequest = new SendSmsRequest().setPhoneNumbers(map.get("mobile").toString())
                    .setSignName(sendsms.get("smsFix").toString())
                    .setTemplateCode(code1)
                    .setTemplateParam(param);
            // 发送短信
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            return WxMiniResponse.ok(sendSmsResponse.getStatusCode());
        }
        return  WxMiniResponse.error(1000,"");
    }

    @Override
    public WxMiniResponse getLng2Address(JSONObject jsonObject){
        Map lnglat= qq2baidu(jsonObject.getDouble("lat"),jsonObject.getDouble("lng"));
        JSONObject  address=lnglat2address(lnglat.get("lng").toString(),lnglat.get("lat").toString());
        return WxMiniResponse.ok(address);
    }

    @Override
    public  WxMiniResponse getcitylist2(JSONObject jsonObject) {
        List<MyPcdDto> list = redisCache.getCacheObject(RedisKeyEnum.REDIS_KEY_MYPCD.getKey()+jsonObject.getString("districtid"));
        if(list==null|| ObjectUtils.isEmpty(list.toArray()) ){
            QueryWrapper<MyPcd> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pid",jsonObject.getInteger("districtid"));
            queryWrapper.eq("status",1);
            queryWrapper.eq("level",jsonObject.getInteger("level"));
            queryWrapper.orderByAsc("sort");
            List<MyPcd>  list1 = myPcdMapper.selectList(queryWrapper);
            list = list1.stream().map(po->{
                MyPcdDto dto = new MyPcdDto();
                BeanUtils.copyProperties(po,dto);
                return dto;
            }).collect(Collectors.toList());
            redisCache.setCacheObject(RedisKeyEnum.REDIS_KEY_MYPCD.getKey()+jsonObject.getString("districtid"),list,2,TimeUnit.HOURS);
            System.out.println(list);
        }
        return WxMiniResponse.ok(list);
    }

    @Autowired
    private MyConfigService myConfigService;
    @Override
    public WxMiniResponse  getcity(JSONObject jsonObject){
        Map map=qq2baidu(jsonObject.getDouble("lat"),jsonObject.getDouble("lng"));
        String lngbd=map.get("lng").toString();
        String latbd=map.get("lat").toString();
        Object address=lnglat2addr(lngbd,latbd,null , null);
        Integer code = getPcdsCode(address.toString(),",");
        MyPcd myPcd =getprovince(code.toString());
        myPcd.setRegion(address.toString());
        MyPcdDto myPcdDto =new MyPcdDto();
        BeanUtils.copyProperties(myPcd, myPcdDto);
        return  WxMiniResponse.ok(myPcdDto);
    }

    @Override
    public WxMiniResponse  getcitylist(JSONObject jsonObject)
    {
        QueryWrapper<MyPcd> wrapper = new QueryWrapper<>();
        wrapper.eq("ishot",1);
        wrapper.eq("status",1);
        wrapper.eq("level",1);
        if(jsonObject.getString("keyword")!=null){
            wrapper.like("name","%"+jsonObject.getString("keyword")+"%");
        }
        wrapper.orderByAsc("sort");
        List<MyPcd> hotlist =myPcdMapper.selectList(wrapper);
        wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);
        wrapper.eq("level",1);
        wrapper.groupBy("en");
        wrapper.orderByAsc("en");
        wrapper.select("en");
        List<MyPcd> enlist =myPcdMapper.selectList(wrapper);
        List<String>  englist = new ArrayList();
        for(int i=0;i<enlist.size();i++){
            englist.add(enlist.get(i).getEn());
        }
        List citylist =new ArrayList<>();
        for (MyPcd myPcd:enlist){
            wrapper = new QueryWrapper<>();
            wrapper.eq("status",1);
            wrapper.eq("level",1);
            wrapper.eq("en",myPcd.getEn());
            if(jsonObject.getString("keyword")!=null){
                wrapper.like("name","%"+jsonObject.getString("keyword")+"%");
            }
            wrapper.orderByAsc("sort");
            List<MyPcd> pcdList = myPcdMapper.selectList(wrapper);
            Map map = new HashMap();
            map.put("name",myPcd.getEn());
            map.put("list",pcdList);
            citylist.add(map);
        }
        wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);
        wrapper.eq("level",1);
        wrapper.orderByDesc("istop","ishot");
        List<MyPcd> sortlist =  myPcdMapper.selectList(wrapper);
        Map map1= new HashMap();
        map1.put("sortList",sortlist);
        map1.put("hotlist",hotlist);
        map1.put("enlist",englist);
        map1.put("citylist",citylist);
        return WxMiniResponse.ok(map1);
    }
    @Override
    public WxMiniResponse getCategoryBox(JSONObject jsonObject){
        QueryWrapper<MyCategoryApp> wrapper = new QueryWrapper<>();
        Integer type = jsonObject.getInteger("type")!=null?jsonObject.getInteger("type"):1;
        Integer level = jsonObject.getInteger("level")!=null?jsonObject.getInteger("level"):1;
        wrapper.eq("`type`",type);
        wrapper.eq("`status`",1);
        wrapper.eq("`level`",level);
        wrapper.orderByAsc("`index`");
        List<MyCategoryApp> list = myCategoryAppMapper.selectList(wrapper);
        return  WxMiniResponse.ok(list);
    }

    private Integer getPcdsCode(String name,String split){
        String[] arr = name.split(split);
        Integer code = 0;
        for(int i=0;i<arr.length;i++){
            QueryWrapper<MyPcd> queryWrapper = new QueryWrapper<>();
            if(code>0){
                queryWrapper.like("code","%"+code+"%");
            }
            queryWrapper.eq("name",arr[i]);
            MyPcd myPcd = myPcdMapper.selectOne(queryWrapper);
            if(myPcd.getCode()>0){
                code = myPcd.getCode();
            }
        }
        return code;
    }

    /**获取地区省*/
    private MyPcd getprovince(String districtid){
        String  pid=districtid.substring(0,2);
        return myPcdService.selectMyPcdByCode(Integer.parseInt(pid));
    }
}
